// index.js
// 获取应用实例
const app = getApp()
import {
  storeList,
  mapLocation
} from '../../utils/api'

Page({
  data: {
    keyword: '',
    stores: [],
    city: '',
    district: '',
  },
  onLoad(options) {
    this.getList()
    this.checkLocation()
  },
  //校验位置权限是否打开
  checkLocation() {
    let that = this;
    //选择位置，需要用户授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.showToast({ //这里提示失败原因
                title: '授权成功！',
                duration: 1500
              })
            },
            fail() {
              // wx.showToast({
              //   title: '需要授权位置信息',
              //   icon: 'none'
              // })
            }
          })
        } else {
          wx.getLocation({
            isHighAccuracy: true,
            type: 'gcj02',
            success (res) {
              mapLocation(res.latitude + ',' + res.longitude).then(rlt => {
                const {city, district} = rlt.result.ad_info
                that.setData({
                  city,
                  district
                })
              })
            }
           })
        }
      }
    })
  },
  getList() {
    storeList(this.data.keyword).then(res => {
      console.log(res)
      res.map(item => {
        item.matrix = item.matrix > 0 ? (parseFloat(item.matrix) / 1000).toFixed(2) : ''
      })
      this.setData({
        stores: res
      })
    })
  },
  bindconfirm(e) {
    this.setData({
      keyword: e.detail.value
    })
    this.getList()
  },
  // 事件处理函数
  toDetail(e) {
    wx.navigateTo({
      url: '/pages/storeDetail/index?storeId=' + e.currentTarget.dataset.id + '&name=' + e.currentTarget.dataset.name,
    })
  },
  toUse() {
    wx.showToast({
      title: '请先选择店铺',
      icon: 'none'
    })
  },
  toRecruit() {
    wx.navigateTo({
      url: '/pages/rucruit/rucruit',
    })
  },
})